package com.rfid;

import android.content.Context;

import com.google.gson.Gson;
import com.rfid.sockethelper.IOHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.socketio.SocketIOClient;
import com.rfid.util.FileUtil;
import com.rfid.webp2plib.SignalClient;
import com.rfid.webp2plib.User;

import java.util.ArrayList;
import java.util.List;

public enum  DefaultServer implements SocketBase.OnReceiveListener,SignalClient.UserListener {

    INSTANCE;
    SocketIOClient mClient;
    Context mContext;
    String mExtraInfo;

    public void start(Context context,String info) {
        mContext = context;
        mExtraInfo = info;
        if (mClient == null) {
            mClient = new SocketIOClient(this);
        }
        mClient.setUserListener(this);
        mClient.connectSignalServer();
    }

    public void setReceiveListener(SocketBase.OnReceiveListener listener) {
        mClient.setReceiveListener(listener);
    }

    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        if (cmd == IOHelper.CMD_QUERY_CONFIGS) {
            List<String> configs = new ArrayList<>();
            configs.add("global");
            configs.add("baidu");
            configs.add("acs");
            configs.add("machine");
            configs.add("monitor");
            configs.add("light");
            Gson gson = new Gson();
            mClient.sendConfigNames(gson.toJson(configs));
        } else if (cmd == IOHelper.CMD_PULL_CONFIG) {
            String json = FileUtil.readFile("/sdcard/shrfid/safedoor/config/" + text[0] + ".json");
            mClient.sendConfig(text[0].toString(), json);
        } else if (cmd == IOHelper.CMD_SET_CONFIG) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String name = text[0].toString();
                    String value = text[1].toString();
                    System.out.println("onConfig txt = " + value);
                    FileUtil.writeFile("/sdcard/shrfid/safedoor/config/" + name + ".json",value);
                }
            }).start();
        }
    }

    @Override
    public void onConnect(String ip, boolean connect) {

    }

    @Override
    public void onLogin(String id, List<User> users) {

    }

    @Override
    public void onConnect(String id) {
        mClient.login(mContext,mExtraInfo);
    }

    @Override
    public void onDisconnect() {

    }

    public void destroy() {
        mClient.release();
    }
}
